package com.example.daibanshiwu.controller;


import com.example.daibanshiwu.Service.HomeService;
import com.example.daibanshiwu.Service.Impl.HomeServiceImpl;
import com.example.daibanshiwu.pojo.FileDTO;
import com.example.daibanshiwu.pojo.Message;
import com.example.daibanshiwu.pojo.excelFileDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@CrossOrigin(origins = "http://localhost:5173")
@RestController
@RequestMapping("/Home")
public class Home {

    // Home.java (Controller)
    @Autowired
    private HomeService homeService; // 应该注入接口

    /**
     * 根据用户ID获取其相关的消息列表
     * 例如，请求URL可以是: GET http://localhost:8081/Home/user/10000001
     * @param userId 从URL路径中获取的用户ID
     * @return 消息列表的JSON格式
     */
    @GetMapping("/user")
    public List<Message> getUserMessages(@RequestParam("userId") Integer userId) {
        // 调用 service 层来完成业务逻辑
        return homeService.getMessagesForUser(userId);
    }

    // 获取紧急事务
    @GetMapping("/urgent")
    public List<Message> getUrgentMessages(@RequestParam("userId") Integer userId) {
        return homeService.getUrgentMessagesForUser(userId);
    }

    //获取教学事务
    @GetMapping("/teachingAffairs")
    public List<Message> getTeachingAffairsMessages(@RequestParam("userId") Integer userId){
        return homeService.getTeachingAffairsMessagesForUser(userId);
    }

    //获取教科研事务
    @GetMapping("/researchAffairs")
    public List<Message> getResearchAffairsMessages(@RequestParam("userId") Integer userId){
        return homeService.getResearchAffairsMessagesForUser(userId);
    }

    //获取学科竞赛
    @GetMapping("/academicCompetition")
    public List<Message> getAcademicCompetitionMessages(@RequestParam("userId") Integer userId){
        return homeService.getAcademicCompetitionForUser(userId);
    }

    //获取学习培训
    @GetMapping("/learningTraining")
    public List<Message> getLearningTrainingMessages(@RequestParam("userId") Integer userId){
        return homeService.getLearningTrainingForUser(userId);
    }

    /**
     * 【新增】更新指定ID事务的状态
     * 前端请求示例: PUT http://localhost:8081/Home/messages/123/status?status=已办
     * @param messageId 从URL路径中获取的事务ID
     * @param newStatus 从请求参数中获取的新状态
     * @return 返回HTTP状态码，例如 200 OK 表示成功
     */
    @PutMapping("/messages/{messageId}/status")
    public ResponseEntity<Void> updateMessageStatus(
            @PathVariable("messageId") int messageId,
            @RequestParam("status") String newStatus) {

        try {
            homeService.markMessageAsHandled(messageId, newStatus);
            // 操作成功，返回 HTTP 200 OK，并且没有响应体
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            // 如果在Service层抛出了异常，可以在这里捕获并返回一个错误状态
            // 例如：log.error("更新状态失败", e);
            return ResponseEntity.internalServerError().build(); // 返回 HTTP 500 Internal Server Error
        }
    }
    //下载excel文件
    @GetMapping("/excelFile")
    public ResponseEntity<byte[]> getexcelFile(@RequestParam("messageId") String messageId) {
        // 1. 调用 Service 获取文件信息 DTO
        excelFileDTO excelfileDTO = homeService.getFileExcelFileByMessageId(messageId);

        // 2. 处理文件不存在的情况
        if (excelfileDTO == null || excelfileDTO.getExcelData() == null) {
            // 返回 404 Not Found
            return ResponseEntity.notFound().build();
        }

        // 3. 构建 HTTP 响应头
        HttpHeaders headers = new HttpHeaders();


        String contentType = excelfileDTO.getContentType() != null ? excelfileDTO.getContentType() : "application/octet-stream";
        headers.setContentType(MediaType.parseMediaType(contentType));

        try {
            String encodedFilename = URLEncoder.encode(excelfileDTO.getExcelName(), "UTF-8").replaceAll("\\+", "%20");
            headers.setContentDisposition(ContentDisposition.builder("inline").filename(encodedFilename).build());
        } catch (UnsupportedEncodingException e) {
            headers.setContentDisposition(ContentDisposition.builder("inline").filename("file").build());
        }

        // 4. 返回最终的 ResponseEntity，包含文件内容、响应头和 HTTP 状态 OK(200)
        return new ResponseEntity<>(excelfileDTO.getExcelData(), headers, HttpStatus.OK);
    }

    }
